package com.ylbh.modules.shortmessage.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylbh.common.pojo.shortmessage.vo.SmsTemplateVO;
import com.ylbh.common.pojo.shortmessage.vo.SmsSelectTemplateVO;
import com.ylbh.common.utils.*;
import com.ylbh.modules.shortmessage.entity.AppSmsTemplate;
import com.ylbh.common.pojo.shortmessage.dto.ShortMessageDTO;
import com.ylbh.common.pojo.shortmessage.vo.ShortMessageVO;
import com.ylbh.common.utils.ExtensionSms;
import com.ylbh.common.utils.PageUtils;
import com.ylbh.modules.shortmessage.mapper.ShortMessageMapper;
import com.ylbh.modules.shortmessage.service.ShortMessageService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * 发送短信
 * @author: czx
 * @date: 2019/10/08 16:09
 */
@Service
public class ShortMessageServiceImpl extends ServiceImpl<ShortMessageMapper, ShortMessageDTO> implements ShortMessageService {

    @Autowired
    private ShortMessageMapper shortMessageMapper;

    /**
     * 根据条件查询出符合用户
     * @param shortMessage
     * @return
     */
    @Override
    public PageUtils queryShortMessageUser(ShortMessageDTO shortMessage) {
        Page<Integer> page = new Page<>(shortMessage.getPage(), shortMessage.getLimit());
        List<ShortMessageVO> list = null;
        if (shortMessage.getSendType() == 1) {
            // 部分用户
            if (shortMessage.getConditionType() == 0) {
                // 根据用户类型
                list = shortMessageMapper.selectUserType(shortMessage.getUserType(), page);
            } else if (shortMessage.getConditionType() == 1) {
                // 根据下单区间
                list = shortMessageMapper.selectOrderTime(shortMessage.getStartTime(), shortMessage.getEndTime(), page);
            } else if (shortMessage.getConditionType() == 2 || shortMessage.getConditionType() == 3) {
                // 表示根据的是注册时间或者活跃时间
                list = shortMessageMapper.selectUserAddTimeOrLastLoginDate(shortMessage.getConditionType(), shortMessage.getStartTime(), shortMessage.getEndTime(), page);
            }
        } else if (shortMessage.getSendType() == 0) {
            // 全部用户
            list = shortMessageMapper.selectShortMessageUser(page);
        } else if (shortMessage.getSendType() == 2) {
            // 指定用户
            list = shortMessageMapper.selectUserByUserName(shortMessage.getUserName());
        }
        return new PageUtils(new Page<ShortMessageVO>().setTotal(page.getTotal()).setRecords(list));
    }

    /**
     * 麦讯通短信群发
     * @param shortMessageDTO
     */
    @Override
    public void sendUser(ShortMessageDTO shortMessageDTO) {
        List<ShortMessageVO> list = null;
        if (shortMessageDTO.getSendType() == 1) {
            // 部分用户
            if (shortMessageDTO.getConditionType() == 0) {
                // 根据用户类型
                list = shortMessageMapper.selectSendByUserType(shortMessageDTO.getUserType());
            } else if (shortMessageDTO.getConditionType() == 1) {
                // 根据下单区间
                list = shortMessageMapper.selectSendOrderTime(shortMessageDTO.getStartTime(), shortMessageDTO.getEndTime());
            } else if (shortMessageDTO.getConditionType() == 2 || shortMessageDTO.getConditionType() == 3) {
                // 表示根据的是注册时间或者活跃时间
                list = shortMessageMapper.selectSendUserAddTimeOrLastLoginDate(shortMessageDTO.getConditionType(), shortMessageDTO.getStartTime(), shortMessageDTO.getEndTime());
            }
        } else if (shortMessageDTO.getSendType() == 0) {
            // 全部用户
            list = shortMessageMapper.selectSendShortMessageUser();
        } else if (shortMessageDTO.getSendType() == 2) {
            // 指定用户
            list = shortMessageMapper.selectUserByUserName(shortMessageDTO.getUserName());
        }
        list = list.stream().collect(
                Collectors.collectingAndThen(Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(ShortMessageVO::getMobile))
                ), ArrayList::new));
        if (null != list) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i).getMobile() + ";");
            }
            ExtensionSms.batchSendSms(sb.toString(), shortMessageDTO.getContent());
        }
    }
    /**
     * 阿里云短信模板添加
     * @param appSmsTemplate
     */
    @Override
    public void addTemplate(AppSmsTemplate appSmsTemplate) {
        SmsTemplateVO smsTemplateVO = AddSmsTemplate.AddTemplate(appSmsTemplate);
        IdWorker idW = new IdWorker();
        if ("OK".equals(smsTemplateVO.getCode()) && "OK".equals(smsTemplateVO.getMessage())){
            appSmsTemplate.setId(idW.nextId());
            appSmsTemplate.setTemplateCode(smsTemplateVO.getTemplateCode());
            shortMessageMapper.insertAppSmsTemplate(appSmsTemplate);
        }
    }

    @Override
    public List<SmsSelectTemplateVO> queryTemplateList() {
        List<AppSmsTemplate > codeList = shortMessageMapper.selectTemplateCode();
        List<SmsSelectTemplateVO> templateList = new ArrayList<>();
        for (AppSmsTemplate list : codeList) {
            if (StringUtils.isNotBlank(list.getTemplateCode())){
                templateList.add(SelectSmsTemplate.SelectTemplate(list.getTemplateCode()));
            }
        }
        return templateList;
    }

    @Override
    public void sendBatchSms(ShortMessageDTO shortMessageDTO) {
        List<ShortMessageVO> list = null;
        if (shortMessageDTO.getSendType() == 1) {
            // 部分用户
            if (shortMessageDTO.getConditionType() == 0) {
                // 根据用户类型
                list = shortMessageMapper.selectSendByUserType(shortMessageDTO.getUserType());
            } else if (shortMessageDTO.getConditionType() == 1) {
                // 根据下单区间
                list = shortMessageMapper.selectSendOrderTime(shortMessageDTO.getStartTime(), shortMessageDTO.getEndTime());
            } else if (shortMessageDTO.getConditionType() == 2 || shortMessageDTO.getConditionType() == 3) {
                // 表示根据的是注册时间或者活跃时间
                list = shortMessageMapper.selectSendUserAddTimeOrLastLoginDate(shortMessageDTO.getConditionType(), shortMessageDTO.getStartTime(), shortMessageDTO.getEndTime());
            }
        } else if (shortMessageDTO.getSendType() == 0) {
            // 全部用户
            list = shortMessageMapper.selectSendShortMessageUser();
        } else if (shortMessageDTO.getSendType() == 2) {
            // 指定用户
            list = shortMessageMapper.selectUserByUserName(shortMessageDTO.getUserName());
        }
        if (null != list) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i).getMobile() + "，");
            }
            ExtensionBatchSms .ExtensionSendSms(sb.toString(), shortMessageDTO.getTemplateCode());
        }
    }


    /**
     * 导出要群发的号码
     * @param request
     * @param response
     */
    @Override
    public void exportShortMessageUser(HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {
        Integer sendType = Integer.parseInt(request.getParameter("sendType"));
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String conditionType = request.getParameter("conditionType");
        String userType = request.getParameter("userType");
        String userName = request.getParameter("userName");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<ShortMessageVO> list = null;
        if (sendType == 1) {
            // 部分用户
            if (Integer.parseInt(conditionType) == 0) {
                // 根据用户类型
                list = shortMessageMapper.selectSendByUserType(Integer.parseInt(userType));
            } else if (Integer.parseInt(conditionType) == 1) {
                // 根据下单区间
                list = shortMessageMapper.selectSendOrderTime(sdf.parse(startTime), sdf.parse(endTime));
            } else if (Integer.parseInt(conditionType) == 2 || Integer.parseInt(conditionType) == 3) {
                // 表示根据的是注册时间或者活跃时间
                list = shortMessageMapper.selectSendUserAddTimeOrLastLoginDate(Integer.parseInt(conditionType), sdf.parse(startTime), sdf.parse(endTime));
            }
        } else if (sendType == 0) {
            // 全部用户
            list = shortMessageMapper.selectSendShortMessageUser();
        } else if (sendType == 2) {
            // 指定用户
            list = shortMessageMapper.selectUserByUserName(userName);
        }
        list = list.stream().collect(
                Collectors.collectingAndThen(Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(ShortMessageVO::getMobile))
                ), ArrayList::new));
        ArrayList<String> list1 = new ArrayList<>();

        SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();
        SXSSFSheet sheet = sxssfWorkbook.createSheet("手机号");
        SXSSFRow headRow = sheet.createRow(0);

        headRow.createCell(0).setCellValue("手机号");
        for (ShortMessageVO vo:list) {
            SXSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
            dataRow.createCell(0).setCellValue(vo.getMobile());
        }
        // 下载导出
        String filename = "群发手机号信息";
        // 设置头信息
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        //一定要设置成xlsx格式
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xls", "UTF-8"));
        //创建一个输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //写入数据
        sxssfWorkbook.write(outputStream);

        // 关闭
        outputStream.close();
        sxssfWorkbook.close();
    }
}
